import { defineStore } from 'pinia';
import type { RouteRecordRaw } from "vue-router";
import { getToken, removeToken } from '../utils/token-utils';
import { ElMessage } from 'element-plus'
import { staticRoutes, allAsyncRouter, anyRoute } from '@/router/routes'
import userinfoApi, { type userinfoModel } from '@/api/userinfo'
import router from "@/router";
import {cloneDeep}from 'lodash'
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
//权限
const filterRouterHandler = (routes: RouteRecordRaw[], routersName: string[]) => {
  let result = routes.filter(route => {

    if (route.children) {
      route.children = filterRouterHandler(route.children, routersName);
    }

    return routersName.includes(route.name as string);
  })

  return result;
}
const addRoutes = (allRoutes: RouteRecordRaw[]) => {
  allRoutes.forEach(route => {
    router.addRoute(route)
  })
}

interface UserInfoState { 
  token: string,
  userinfo: userinfoModel,
  menuRoutes: RouteRecordRaw[]
}
const initUserinfo = (): userinfoModel => ({
  avatar: '',
  name: '',
  buttons: [],
  roles: [],
  routes: []
})
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    userinfo: initUserinfo(),
    menuRoutes: []
  }),
  actions: {
    //登录
    async login(username: string, password: string) {
      try {
        let res = await userinfoApi.login({ username, password })
        console.log(res);
        ElMessage.success('登录返回数据成功')
        this.token = res.token
      } catch (error) {
        ElMessage.error('获取登录数据失败')
        return Promise.reject(error)
      }

    },
    //获取用户信息
    async getInfo() {
      try {
        let res = await userinfoApi.info()
        console.log(res);
        this.userinfo = res
        //权限

        const filterRouter = filterRouterHandler(cloneDeep(allAsyncRouter), res.routes)
        const allRputer = staticRoutes.concat(filterRouter, anyRoute);
        this.menuRoutes = allRputer
        addRoutes(allRputer)
      } catch (error) {
        ElMessage.error('获取个人信息数据失败')
        return Promise.reject(error)
      }
    },
    //退出
    async logout() {
      try {
        let res = await userinfoApi.logout()
        this.reset()
      } catch (error) {
        ElMessage.error('获取个人信息数据失败')
        return Promise.reject(error)
      }
    },
    //初始化
    reset() {
      removeToken()
      this.token = ''
      this.userinfo = initUserinfo();

    },
  },
});
